package com.fenghao.subject.domain.service.impl;

import com.fenghao.subject.domain.convert.SubjectInfoConvert;
import com.fenghao.subject.domain.entity.SubjectInfoBO;
import com.fenghao.subject.domain.handler.subject.SubjectTypeHandleFactory;
import com.fenghao.subject.domain.handler.subject.SubjectTypeHandler;
import com.fenghao.subject.domain.service.SubjectInfoDomainService;
import com.fenghao.subject.infra.basic.entity.SubjectInfo;
import com.fenghao.subject.infra.basic.entity.SubjectMapping;
import com.fenghao.subject.infra.basic.service.SubjectInfoService;
import com.fenghao.subject.infra.basic.service.SubjectMappingService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * SubjectInfoDomainServiceImpl
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class SubjectInfoDomainServiceImpl implements SubjectInfoDomainService {
    private final SubjectInfoService subjectInfoService;

    private final SubjectTypeHandleFactory subjectTypeHandleFactory;
    private final SubjectMappingService subjectMappingService;

    /**
     * 新增题目
     */
    @Override
    @Transactional
    public void addSubject(SubjectInfoBO subjectInfoBO) {
        SubjectInfo subjectInfo = SubjectInfoConvert.INSTANCE.convertBoToInfo(subjectInfoBO);
        // 插入题目共享信息
        subjectInfoService.insert(subjectInfo);
        Integer subjectType = subjectInfo.getSubjectType();
        // 根据题目类型选择策略
        SubjectTypeHandler subjectTypeHandler = subjectTypeHandleFactory.getSubjectTypeHandler(subjectType);
        subjectTypeHandler.addSubject(subjectInfoBO);

        List<SubjectMapping> subjectMappingList = getSubjectMappingList(subjectInfoBO, subjectInfo);
        // 批量添加
        subjectMappingService.insertBatch(subjectMappingList);
    }

    /**
     * 抽取方法 : getSubjectMappingList()
     */
    private static List<SubjectMapping> getSubjectMappingList(SubjectInfoBO subjectInfoBO, SubjectInfo subjectInfo) {
        List<Integer> categoryIdList = subjectInfoBO.getCategoryIdList();
        List<Integer> labelIdList = subjectInfoBO.getLabelIdList();

        List<SubjectMapping> subjectMappingList = new ArrayList<>();
        categoryIdList.forEach(categoryId -> labelIdList.forEach(labelId -> {
            SubjectMapping subjectMapping = SubjectMapping.builder()
                    .subjectId(subjectInfo.getId())
                    .categoryId(Long.valueOf(categoryId))
                    .labelId(Long.valueOf(labelId)).build();
            subjectMappingList.add(subjectMapping);
        }));
        return subjectMappingList;
    }


}
